<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Price_Line extends ORM
{
    /**
     * @param $params
     * @return array
     * 插入报价信息
     */
    public static function set_calendar_quote($params)
    {
        $params = json_decode($params,true);
        $start_time = strtotime($params['start_time']);
        $end_time = strtotime($params['end_time']);

        $total_number = DB::select(DB::expr('min(number) AS number'))->from('line_suit_number')
                          ->where("suit_id={$params['suit_id']} and number!='-1' and day>={$start_time} and day<={$end_time}")
                          ->execute()->get('number');
        if(($params['number']>$total_number || $params['number']=='-1') && $total_number>0){
            $date = DB::select()->from('line_suit_number')
                      ->where("suit_id={$params['suit_id']} and number={$total_number} and day>={$start_time} and day<={$end_time}")
                      ->execute()->get('day');
            return array(
                'status' => false,
                'msg'    => date('Y-m-d',$date).'当前时间，库存不支持所设限购数',
            );
        }

        $day_num = ($end_time-$start_time)/86400;
        $product_id = DB::select()->from('line_suit')->where("id={$params['suit_id']}")->execute()->get('lineid');

        $room_balance       = $params['roombalance']?$params['roombalance']:0;
        $number             = $params['number']?$params['number']:0;
        $propgroup          = implode(',',$params['propgroup']);

        $insert_arr = array();
        $update_arr = array(
            'adultbasicprice'    => "adultbasicprice = CASE ",
            'adultprofit'        => "adultprofit = CASE ",
            'adultprice'         => "adultprice = CASE ",
            'childbasicprice'    => "childbasicprice = CASE ",
            'childprofit'        => "childprofit = CASE ",
            'childprice'         => "childprice = CASE ",
            'oldbasicprice'      => "oldbasicprice = CASE ",
            'oldprofit'          => "oldprofit = CASE ",
            'oldprice'           => "oldprice = CASE ",
            'people4_basicprice' => "people4_basicprice = CASE ",
            'people4_profit'     => "people4_profit = CASE ",
            'people4_price'      => "people4_price = CASE ",
            'people5_basicprice' => "people5_basicprice = CASE ",
            'people5_profit'     => "people5_profit = CASE ",
            'people5_price'      => "people5_price = CASE ",
            'people6_basicprice' => "people6_basicprice = CASE ",
            'people6_profit'     => "people6_profit = CASE ",
            'people6_price'      => "people6_price = CASE ",
            'number'             => "number = CASE ",
            'propgroup'          => "propgroup = CASE ",
            'roombalance'        => "roombalance = CASE ",
        );

        $adultprice = bcadd($params['adultbasicprice'],$params['adultprofit'],2);
        $childprice = bcadd($params['childbasicprice'],$params['childprofit'],2);
        $oldprice   = bcadd($params['oldbasicprice'],$params['oldprofit'],2);
        $people4_price = bcadd($params['people4_basicprice'],$params['people4_profit'],2);
        $people5_price = bcadd($params['people5_basicprice'],$params['people5_profit'],2);
        $people6_price = bcadd($params['people6_basicprice'],$params['people6_profit'],2);

        try {

        } catch (Exception $e) {

        }
        $update_id = array();
        $update_day = array();
        for($i=0;$i<=$day_num;$i++){
            $start_time = $i>0?$start_time+86400:$start_time;
            $num = DB::select()->from('line_suit_number')
                ->where('suit_id', '=', $params['suit_id'])
                ->and_where('day', '=', $start_time)
                ->execute()
                ->get('number');
            if(!$num){
                continue;
            }
            if($num<$params['number'] && $num!='-1'){
                continue;
            }
            $is_exist = DB::select()->from('line_suit_price')
                          ->where("suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']}")
                          ->execute()->current();
            $state = false;
            switch ($params['price_rule'])
            {
                case 1://全时段
                    $state = true;
                    break;
                case 2://按周
                    $week = date('w',$start_time)>0?date('w',$start_time):7;
                    if(in_array($week,$params['week_val'])){
                        $state = true;
                    }
                    break;
                case 3://按天
                    $month = date('j',$start_time);
                    if(in_array($month,$params['month_val'])){
                        $state = true;
                    }
                    break;
            }
            if(!$state){
                continue;
            }
            if($is_exist){
                array_push($update_id,$is_exist['suitid']);
                array_push($update_day,$is_exist['day']);

                $sql = "WHEN suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']}";
                $update_arr['adultbasicprice']    .= $sql." THEN '{$params['adultbasicprice']}' ";
                $update_arr['adultprofit']        .= $sql." THEN '{$params['adultprofit']}' ";
                $update_arr['adultprice']         .= $sql." THEN '{$adultprice}' ";
                $update_arr['childbasicprice']    .= $sql." THEN '{$params['childbasicprice']}' ";
                $update_arr['childprofit']        .= $sql." THEN '{$params['childprofit']}' ";
                $update_arr['childprice']         .= $sql." THEN '{$childprice}' ";
                $update_arr['oldbasicprice']      .= $sql." THEN '{$params['oldbasicprice']}' ";
                $update_arr['oldprofit']          .= $sql." THEN '{$params['oldprofit']}' ";
                $update_arr['oldprice']           .= $sql." THEN '{$oldprice}' ";
                $update_arr['people4_basicprice'] .= $sql." THEN '{$params['people4_basicprice']}' ";
                $update_arr['people4_profit']     .= $sql." THEN '{$params['people4_profit']}' ";
                $update_arr['people4_price']      .= $sql." THEN '{$people4_price}' ";
                $update_arr['people5_basicprice'] .= $sql." THEN '{$params['people5_basicprice']}' ";
                $update_arr['people5_profit']     .= $sql." THEN '{$params['people5_profit']}' ";
                $update_arr['people5_price']      .= $sql." THEN '{$people5_price}' ";
                $update_arr['people6_basicprice'] .= $sql." THEN '{$params['people6_basicprice']}' ";
                $update_arr['people6_profit']     .= $sql." THEN '{$params['people6_profit']}' ";
                $update_arr['people6_price']      .= $sql." THEN '{$people6_price}' ";
                $update_arr['number']             .= $sql." THEN '{$number}' ";
                $update_arr['propgroup']          .= $sql." THEN '{$propgroup}' ";
                $update_arr['roombalance']          .= $sql." THEN '{$room_balance}' ";
            }else{
                $value_arr = array(
                    $product_id,
                    $params['suit_id'],
                    $start_time,
                    $params['adultbasicprice'],
                    $params['adultprofit'],
                    $adultprice,
                    $params['childbasicprice'],
                    $params['childprofit'],
                    $childprice,
                    $params['oldbasicprice'],
                    $params['oldprofit'],
                    $oldprice,
                    $params['people4_basicprice'],
                    $params['people4_profit'],
                    $people4_price,
                    $params['people5_basicprice'],
                    $params['people5_profit'],
                    $people5_price,
                    $params['people6_basicprice'],
                    $params['people6_profit'],
                    $people6_price,
                    $room_balance,
                    $number,
                    $params['channel_id'],
                    "'".$propgroup."'"
                );
                $insert_sql = "(".implode(',',$value_arr).")";
                array_push($insert_arr,$insert_sql);
            }
        }

        if(count($insert_arr)>0){
            $field_arr = array(
                'lineid',
                'suitid',
                'day',
                'adultbasicprice',
                'adultprofit',
                'adultprice',
                'childbasicprice',
                'childprofit',
                'childprice',
                'oldbasicprice',
                'oldprofit',
                'oldprice',
                'people4_basicprice',
                'people4_profit',
                'people4_price',
                'people5_basicprice',
                'people5_profit',
                'people5_price',
                'people6_basicprice',
                'people6_profit',
                'people6_price',
                'roombalance',
                'number',
                'supplier_channel_id',
                'propgroup',
            );
            $insert_sql = "INSERT INTO sline_line_suit_price(`".implode('`,`',$field_arr)."`) VALUES ";
            $insert_sql.= implode(',',$insert_arr);
            $result = DB::query(1, $insert_sql)->execute();
        }
        if(count($update_id)>0){
            $update_sql = "UPDATE sline_line_suit_price SET ";
            $update_id = implode(',',$update_id);
            $update_day = implode(',',$update_day);
            foreach ($update_arr as $k=>$v){
                $update_sql.= $v."ELSE {$k} END,";
            }
            $update_sql = substr($update_sql,0,strlen($update_sql)-1);
            $update_sql.= " WHERE suitid IN({$update_id}) and day IN({$update_day}) ";
            $result = DB::query(1, $update_sql)->execute();
        }

        return array(
            'status' => $result || $result===0?true:false,
            'msg'    => $result || $result===0?'设置成功':'设置失败',
        );
    }

    public static function set_single_price($params)
    {
        $params = json_decode($params,true);
        $day = strtotime($params['set_date']);

        $total_number = DB::select()->from('line_suit_number')->where("suit_id={$params['suit_id']} and day={$day}")->execute()->get('number');
        if(empty($total_number)){
            return array(
                'status' => false,
                'msg'    => '当前日期没有总库存！',
            );
        }
        if($params['number']>$total_number && $total_number!='-1'){
            return array(
                'status' => false,
                'msg'    => '限购数不得大于总库存',
            );
        }
        $propgroup_str = implode(',',$params['propgroup']);
        $data = array(
            'childbasicprice'    => $params['childbasicprice'],
            'childprofit'        => $params['childprofit'],
            'childprice'         => bcadd($params['childbasicprice'],$params['childprofit'],2),
            'adultbasicprice'    => $params['adultbasicprice'],
            'adultprofit'        => $params['adultprofit'],
            'adultprice'         => bcadd($params['adultbasicprice'],$params['adultprofit'],2),
            'oldbasicprice'      => $params['oldbasicprice'],
            'oldprofit'          => $params['oldprofit'],
            'oldprice'           => bcadd($params['oldbasicprice'],$params['oldprofit'],2),
            'people4_basicprice' => $params['people4_basicprice'],
            'people4_profit'     => $params['people4_profit'],
            'people4_price'      => bcadd($params['people4_basicprice'],$params['people4_profit'],2),
            'people5_basicprice' => $params['people5_basicprice'],
            'people5_profit'     => $params['people5_profit'],
            'people5_price'      => bcadd($params['people5_basicprice'],$params['people5_profit'],2),
            'people6_basicprice' => $params['people6_basicprice'],
            'people6_profit'     => $params['people6_profit'],
            'people6_price'      => bcadd($params['people6_basicprice'],$params['people6_profit'],2),
            'roombalance'        => $params['roombalance'],
            'number'             => $params['number_type']==1?-1:$params['number'],
            'propgroup'          => $propgroup_str,
        );
        $exists = DB::select()->from('line_suit_price')
                    ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
                    ->execute()
                    ->as_array();
        if($exists){
            $result = DB::update('line_suit_price')->set($data)
                        ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
                        ->execute();
        }else{
            $line_suit=DB::select()
                              ->from('line_suit')->where("id={$params['suit_id']} ")
                                ->execute()
                                ->current();
            $data['lineid']=$line_suit['lineid'];
            $data['suitid']=$params['suit_id'];
            $data['day']=$day;
            $result = DB::insert('line_suit_price',array_keys($data))->values(array_values($data))->execute();
        }


        return array(
            'status'             => $result || $result===0?true:false,
            'msg'                => $result || $result===0?'设置成功':'设置失败',
            'childprice'         => $data['childprice'],
            'adultprice'         => $data['adultprice'],
            'oldprice'           => $data['oldprice'],
            'people4_price'      => $data['people4_price'],
            'people5_price'      => $data['people5_price'],
            'people6_price'      => $data['people6_price'],
            'roombalance'        => $data['roombalance'],
            'number'             => $data['number'],
            'date'               => $params['set_date'],
            'propgroup'          => json_encode($params['propgroup'])
        );
    }

    /**
     * @param $params
     * @return array
     * 根据渠道id获取报价信息
     */
    public static function get_suit_price($params)
    {
        $params = json_decode($params,true);
        $year = $params['year'];
        $month = $params['month'];


        if($year && $month){
            $start_time = strtotime($year.'-'.$month.'-1');
            $last_day = date('Y-m-t',$start_time);
            $end_time = strtotime($last_day);
        }else{
            $day = strtotime(date('Ymd'));
            $calendar = DB::select()->from('line_suit_price')
                          ->where("suitid={$params['suit_id']} and day>={$day}")
                          ->order_by('day','ASC')
                          ->execute()
                          ->current();
            $start_time =$calendar['day']?$calendar['day']:$day;
            $last_day = date('Y-m-t',$start_time);
            $end_time = strtotime($last_day);
        }


        $allowed_days = array();
        $list = DB::select()->from('line_suit_price')
                  ->where("
                suitid='{$params['suit_id']}' 
                and day>={$start_time} 
                and day<={$end_time} 
                and supplier_channel_id={$params['channel_id']}
            ")
                  ->execute()
                  ->as_array();
        foreach ($list as $key=>&$row)
        {
            $row['date'] = date('Y-m-d',$row['day']);
            $allowed_days[] = $row['date'];
            $row['number'] = $row['number']==-1?'不限':$row['number'];
        }

        return array(
            'list'         => $list,
            'starttime'    => date('Y-m-d',$start_time),
            'allowed_days' => $allowed_days
        );
    }

    /**
     * @param $params
     * @return bool[]
     * 清除报价
     */
    public static function delete_price($params)
    {
        $params = json_decode($params,true);
        DB::delete('line_suit_price')->where("suitid={$params['suit_id']} and supplier_channel_id IN({$params['channel_id']})")->execute();

        return array(
            'status' => true,
        );
    }

    /**
     * @param $params
     * @return array
     * 渠道产品列表
     */
    public static function channel_product_list($params)
    {
        $params = json_decode($params,true);
        $date = strtotime(date('Ymd'));
        $page = ($params['page']-1)*$params['page_size'];

        $sql = "SELECT a.id,a.title,a.status,a.ishidden FROM sline_line AS a ";
        $sql.= "LEFT JOIN sline_line_suit_price AS b ON(a.id=b.lineid) ";
        $sql.= "WHERE a.supplierlist={$params['supplier_id']} AND b.day>={$date} ";
        if($params['keyword']){
            $sql.= "AND (a.title LIKE '%{$params['keyword']}%' OR a.id='{$params['keyword']}') ";
        }
        $sql.= "GROUP BY a.id ";
        $sql.= "ORDER BY a.modtime DESC,a.addtime DESC ";
        $total = DB::query(1, $sql)->execute()->count();
        $sql.= "LIMIT {$page},{$params['page_size']} ";
        $list = DB::query(1, $sql)->execute()->as_array();
        if(!$list){
            return array('status'=>false,'msg'=>'没有匹配的线路产品！');
        }
        foreach ($list as &$v){
            $v['status_name'] = Model_Supplier::status_name($v['status']);
            $max_day = DB::select(DB::expr('max(day) AS day') )->from('line_suit_price')->where("day>{$date} and lineid={$v['id']}")->execute()->get('day');
            $v['time_validity'] = date('Y-m-d',$max_day);
        }

        return array(
            'status'     => true,
            'list'       => $list,
            'total_page' => ceil($total/$params['page_size'])
        );
    }

    public static function rm_oneday_price($params)
    {
        $params = json_decode($params,true);
        $day = strtotime($params['set_date']);
        DB::delete('line_suit_price')
            ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id IN({$params['channel_id']})")
            ->execute();

        return array(
            'date'=>$params['set_date'],
            'status' => true,
            'msg' =>  '单日删除成功',
        );
    }

}